/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package simplepushserver.file;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import simplepushserver.gui.Notifier;

/**
 * @author Filip
 */
public class Folder {
    
    public static File search(List<File> folderList, String name,Notifier n){
        for (Iterator it = folderList.iterator(); it.hasNext();){
            File dir = (File)it.next();
            if(n!=null) n.onNotification("Searching for "+name+" in "+dir.getAbsolutePath());
            File result = search(dir,name);
            if(result!=null)return result;
        }
        if(n!=null)n.onNotification("Couldn't find file \""+name+"\"");
        return null;
    }
    public static File search(File folder,String name){
        name = name.toLowerCase();
        int i = 0;
        for(File f : folder.listFiles()){
            i++;
            if(f.getName().toLowerCase().contains(name)){
                return f;
            }else if(f.isDirectory()){
                File childSearch = search(f, name);
                if(childSearch!=null){
                    return childSearch;
                }
            }
        }
        return null;
    }

    private static boolean contains(String searchS, String str){
        char[] searchArr = searchS.toLowerCase().toCharArray();
        char[] chrArr = str.toLowerCase().toCharArray();
        int sInt = 0;
        for (int i=0;i<chrArr.length; i++) {
            if(chrArr[i]==searchArr[sInt]){
                sInt++;
                if(sInt==searchArr.length){
                    return true;
                }
            }else if(sInt>0){
                sInt=0;
            }
        }
        return false;
    }
    
    public static File folderRootSearch(List<File> folders, String filename){
        Iterator<File> it = folders.iterator();
        while (it.hasNext()) {
            File f = new File(it.next(),filename);
            if(f.exists()){
                return f;
            }
        }return null;
    }
}
